<script lang="ts" setup name="messageRecharge">
import { onMounted, onUnmounted, ref } from "vue";
import LaiHeader from "@/components/lai-header/index.vue";
import { getMessageStoreAPI, submitApplyAPI, getQRcodeAPI, getPayStatusAPI } from "@/api/modules/system";
import { System } from "@/api/interface/index";
import { useMessage } from "@/hooks/useMessage";
import { ElForm, ElMessage } from "element-plus";
import QRcode from "qrcode";

onMounted(() => {
  getMessageStore();
});
const messageInfo = ref<System.MessageStore>({
  checkTime: "",
  facCode: "",
  smsCheckFlag: 0,
  smsCount: 0,
  smsSign: "",
  smsSignApplyTime: "",
  storeId: 0
});

interface RechargeList {
  count: number;
  gift: number;
  money: number;
}

const rechargeList = ref<RechargeList[]>([]);
const getMessageStore = async () => {
  const res = await getMessageStoreAPI();
  messageInfo.value = res.data.detail;
  rechargeList.value = res.data.list;
};

const formData = ref<{
  money: number | null;
  count: number | null;
  gift: number | null;
}>({
  money: null,
  count: null,
  gift: null
});
const rules = ref<any>({
  money: [{ required: true, message: "请选择充值金额" }]
});

const apply = async () => {
  await submitApplyAPI({
    // 提交短信签名
    id: messageInfo.value.storeId,
    smsSign: messageInfo.value.smsSign
  });
  useMessage("提交申请成功", "success");
};

const checkAmount = (index: number) => {
  formData.value.money = rechargeList.value[index].money;
  formData.value.count = rechargeList.value[index].count;
  formData.value.gift = rechargeList.value[index].gift;
};
const formRef = ref<InstanceType<typeof ElForm> | null>(null);
const orderNo = ref(0);
const onConfirm = async () => {
  await formRef.value?.validate();
  const res = await getQRcodeAPI({
    params: {
      money: formData.value.money,
      smsCount: (formData.value.count ? formData.value.count : 0) + (formData.value.gift ? formData.value.gift : 0)
    },
    payment_code: "qrcode",
    payment_type: 20
  });
  orderNo.value = res.otherData;
  // 在组件挂载后可以访问到 canvas 元素
  getQRcode("", res.data);
};

const dialogVisible = ref(false);
const qrCodeCanvas = ref();
const num = ref(0);
let timer;
let payTimer;
const getQRcode = (msg: string, QRcodeMsg: string) => {
  let opts = {
    errorCorrectionLevel: "H", //容错级别
    type: "image/png", //生成的二维码类型
    quality: 0.3, //二维码质量
    margin: 5, //二维码留白边距
    width: 200, //宽
    height: 180, //高
    text: "", //二维码内容
    color: {
      dark: "#000", //前景色
      light: "#fff" //背景色
    }
  };
  QRcode.toCanvas(qrCodeCanvas.value, QRcodeMsg, function (error: any) {
    if (error) {
      console.log(error, "二维码生成出错");
      throw new Error(error);
    } else {
      clearInterval(timer);
      clearInterval(payTimer);
      dialogVisible.value = true;
      num.value = 120;
      timer = setInterval(() => {
        if (num.value === 0) {
          clearInterval(timer);
          clearInterval(payTimer);
          dialogVisible.value = false;
        } else {
          num.value--;
        }
      }, 1000);
      payTimer = setInterval(() => {
        getPayStatus();
      }, 2000);
    }
  });
};

const getPayStatus = async () => {
  const res = await getPayStatusAPI({ ordNo: orderNo.value });
  if (res.data) {
    clearInterval(timer);
    clearInterval(payTimer);
    dialogVisible.value = false;
    ElMessage({
      message: "支付成功",
      type: "success",
      duration: 2000
    });
    setTimeout(() => {
      getMessageStore();
    }, 2000);
  }
};

onUnmounted(() => {
  clearInterval(timer);
  clearInterval(payTimer);
});
</script>
<template>
  <div class="recharge-container">
    <LaiHeader title="短信充值" :height="70"></LaiHeader>

    <div class="recharge-form">
      <div>会员充值、消费时给会员发送提示短信</div>
      <div style="margin-top: 5px; font-size: 14px; color: #6d6d6d">剩余短信： {{ messageInfo.smsCount }}</div>
      <el-form ref="formRef" :model="formData" :rules="rules" style="margin-top: 20px" label-width="100">
        <el-form-item label="短信签名：">
          <el-input :disabled="messageInfo.smsCheckFlag === 2" v-model="messageInfo.smsSign" style="width: 20%" />
          <el-button @click="apply" v-if="messageInfo.smsCheckFlag !== 2" style="margin-left: 5px">
            <el-icon><MessageBox /></el-icon>提交申请
          </el-button>
        </el-form-item>
        <el-form-item label="短信数量：" prop="count">
          <el-input v-model="formData.count" disabled style="width: 20%" />
        </el-form-item>
        <el-form-item label="赠送数量：" prop="gift">
          <el-input disabled v-model="formData.gift" style="width: 20%" />
        </el-form-item>
        <el-form-item label="充值金额：" prop="money">
          <el-input v-model="formData.money" disabled style="width: 20%" />
          <el-button @click="checkAmount(index)" v-for="(item, index) in rechargeList" :key="index" style="margin-left: 5px">
            {{ item.money }}元
          </el-button>
        </el-form-item>

        <el-form-item>
          <el-button @click="onConfirm" type="primary">充值</el-button>
        </el-form-item>
      </el-form>

      <div style="width: 25%; padding: 20px; font-size: 14px; color: #6d6d6d">
        短信例子： 尊敬客户,您尾号8888卡号消费-100.00元.可用储值:900.00元【XXXXX】 【XXXXX】是短信签名
        签名为商户名称，需要更改时请注意。
      </div>
      <div v-show="dialogVisible" style="margin-left: 30px">
        <div style="padding-left: 20px; color: #f3c45d">请扫描二维码进行充值</div>
        <canvas ref="qrCodeCanvas"></canvas>
        <div style="margin-left: 80px">{{ num + "s" }}</div>
      </div>
    </div>
    <!-- <el-dialog v-model="dialogVisible" title="请扫码支付" width="500">
      <div style="display: flex; justify-content: center; margin-top: 30px">
      </div>
    </el-dialog> -->
  </div>
</template>

<style lang="scss" scoped>
div {
  box-sizing: border-box;
}
.recharge-container {
  height: 100%;
  overflow: hidden;
  .recharge-form {
    height: calc(100% - 80px);
    padding: 20px;
    background-color: #ffffff;
    border-radius: 5px;
  }
}
</style>
